<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人资料</span>
        </div>
      </template>
      
      <div class="profile-content" v-if="!loading">
        <!-- 头像部分 -->
        <div class="avatar-section">
          <el-upload
            class="avatar-uploader"
            action=""
            :http-request="handleAvatarUpload"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="userInfo.avatar && userInfo.avatar !== 'null' && userInfo.avatar !== 'undefined'" :src="userInfo.avatar" class="avatar" />
            <img v-else src="/default-avatar.png" class="avatar" />
          </el-upload>
          <div class="avatar-hint">点击更换头像</div>
        </div>
        
        <!-- 表单部分 -->
        <el-form ref="formRef" :model="userForm" :rules="rules" class="profile-form">
          <el-form-item label="用户名" prop="username" label-for="username">
            <el-input v-model="userForm.username" disabled id="username"></el-input>
          </el-form-item>
          
          <el-form-item label="昵称" prop="nickname" label-for="nickname">
            <el-input v-model="userForm.nickname" id="nickname"></el-input>
          </el-form-item>
          
          <el-form-item label="邮箱" prop="email" label-for="email">
            <el-input v-model="userForm.email" type="email" id="email"></el-input>
          </el-form-item>
          
          <el-form-item label="手机号" prop="phone" label-for="phone">
            <el-input v-model="userForm.phone" id="phone"></el-input>
          </el-form-item>
          
          <el-form-item label="性别" prop="gender" label-for="gender-male">
            <el-radio-group v-model="userForm.gender">
              <el-radio label="male" id="gender-male">男</el-radio>
              <el-radio label="female" id="gender-female">女</el-radio>
              <el-radio label="other" id="gender-other">其他</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        
        <!-- 用户详细信息部分 -->
        <div class="profile-detail-section">
          <h3>详细信息</h3>
          <el-form-item label="个人简介" prop="profile.bio" label-for="bio">
            <el-input v-model="userForm.profile.bio" type="textarea" :rows="3" id="bio"></el-input>
          </el-form-item>
          
          <el-form-item label="兴趣爱好" prop="profile.interests" label-for="interests">
            <el-input v-model="userForm.profile.interests" placeholder="多个兴趣用逗号分隔" id="interests"></el-input>
          </el-form-item>
        </div>
        
        <!-- 按钮组 -->
        <div class="form-buttons">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            保存修改
          </el-button>
        </div>
        
        <!-- 账号安全设置 -->
        <div class="account-security">
          <h3>账号安全</h3>
          <div class="security-item">
            <span>修改密码</span>
            <el-button type="text" @click="handleChangePassword">立即修改</el-button>
          </div>
          <div class="security-item">
            <span>收货地址</span>
            <el-button type="text" @click="handleGoToAddress">查看/管理</el-button>
          </div>
        </div>
      </div>
      
      <div v-else class="loading" v-loading="loading" element-loading-text="加载中...">
      </div>
    </el-card>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="400px"
    >
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules">
        <el-form-item label="当前密码" prop="currentPassword" label-for="currentPassword">
          <el-input v-model="passwordForm.currentPassword" type="password" id="currentPassword"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword" label-for="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" id="newPassword"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword" label-for="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" id="confirmPassword"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePasswordSubmit" :loading="passwordSubmitting">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { userApi } from '../api'
import { getToken, removeToken } from '../utils/auth'

// 初始化用户信息，确保包含所有必要字段的默认值
const userInfo = reactive({})
const userForm = reactive({
  username: '',
  email: '',
  nickname: '',
  phone: '',
  gender: 'male',
  birthday: '',
  student_id: '',
  major: '',
  grade: '',
  dormitory: '',
  profile: {
    bio: '',
    interests: ''
  }
})
const originalForm = reactive({})
const loading = ref(false)
const submitting = ref(false)
const formRef = ref(null)

// 密码修改相关
const passwordDialogVisible = ref(false)
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const passwordSubmitting = ref(false)
const passwordFormRef = ref(null)

const router = useRouter()

// 表单验证规则
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  nickname: [{ max: 20, message: '昵称长度不能超过20个字符', trigger: 'blur' }],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的手机号',
      trigger: 'blur'
    }
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }]
}

// 密码验证规则
const passwordRules = {
  currentPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
const fetchUserInfo = async () => {
  loading.value = true
  try {
    const response = await userApi.getUserInfo()
    console.log('获取用户信息:', response)
    console.log('头像URL:', response.data.avatar)
    console.log('头像URL类型:', typeof response.data.avatar)
    
    // 深拷贝响应数据
    const userData = { ...response.data }
    
    // 处理头像URL，确保它是有效的URL格式
    if (userData.avatar) {
      // 如果头像URL不是以http开头的完整URL，添加基础URL
      if (typeof userData.avatar === 'string' && !userData.avatar.startsWith('http')) {
        // 检查是否已经以/开头
        const baseUrl = import.meta.env.VITE_APP_API_BASE_URL || '/api'
        if (!userData.avatar.startsWith('/')) {
          userData.avatar = baseUrl + '/' + userData.avatar
        } else {
          // 如果以/开头但不是完整URL，可能需要调整路径
          // 检查是否已经包含了正确的路径
          if (!userData.avatar.startsWith('/media/')) {
            userData.avatar = baseUrl + userData.avatar
          }
        }
        console.log('处理后的头像URL:', userData.avatar)
      }
    }
    
    // 更新用户信息
    Object.assign(userInfo, userData)
    
    // 确保userForm包含profile对象
    const userFormData = { ...userData };
    if (!userFormData.profile) {
      userFormData.profile = {};
    }
    
    Object.assign(userForm, userFormData)
    Object.assign(originalForm, userFormData)
    
    ElMessage.success('获取用户信息成功')
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败，请稍后重试')
    
    // 如果未登录或登录已过期，跳转到登录页
    if (error.response && error.response.status === 401) {
      removeToken()
      router.push('/login')
    }
  } finally {
    loading.value = false
  }
}

// 处理表单提交
const handleSubmit = async () => {
  try {
    formRef.value.validate(async (valid) => {
      if (valid) {
        submitting.value = true
        try {
          // 使用普通对象格式提交，确保与后端API期望的格式匹配
          // 深拷贝userForm对象，避免直接修改原始数据
          const submitData = { ...userForm };
          
          // 删除avatar字段，头像上传通过专用API处理
          delete submitData.avatar;
          
          // 处理性别字段，确保格式正确
          if (!submitData.gender) {
            submitData.gender = 'male'; // 设置默认值
          }
          
          // 先更新基本用户信息
          const userResponse = await userApi.updateUserInfo(submitData);
          console.log('更新用户基本信息响应:', userResponse)
          
          // 然后更新用户详细信息（如果有profile数据）
          if (userForm.profile) {
            // 准备profile数据
            const profileData = { ...userForm.profile };
            
            // 处理interests字段，将字符串转换为数组
            if (profileData.interests && typeof profileData.interests === 'string') {
              profileData.interests = profileData.interests.split(',').map(item => item.trim()).filter(item => item);
            }
            
            const profileResponse = await userApi.updateUserProfileDetail(profileData);
            console.log('更新用户详细信息响应:', profileResponse)
          }
          
          // 重新获取完整用户信息以更新本地缓存
          await fetchUserInfo();
          
          ElMessage.success('保存成功')
        } catch (error) {
          console.error('更新用户信息失败:', error)
          // 显示更详细的错误信息
          if (error.response && error.response.data) {
            let errorMessage = '保存失败: ';
            if (error.response.data.message) {
              errorMessage += error.response.data.message;
            } else if (error.response.data.error) {
              errorMessage += error.response.data.error;
            } else {
              errorMessage += '未知错误';
            }
            ElMessage.error(errorMessage);
          } else {
            ElMessage.error('保存失败，请稍后重试');
          }
        } finally {
          submitting.value = false
        }
      }
    })
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('保存失败，请稍后重试')
    submitting.value = false
  }
}

// 取消编辑
const cancelEdit = () => {
  Object.assign(userForm, originalForm)
  ElMessage.success('已取消编辑')
}

// 处理头像上传
const handleAvatarUpload = async (options) => {
  const { file } = options
  try {
    // 显示上传中状态
    options.onProgress({ percent: 50 })
    
    // 调用头像上传API
    const response = await userApi.uploadUserAvatar(file)
    
    // 更新用户信息中的头像URL
    userInfo.avatar = response.data.avatar
    
    // 提示上传成功
    ElMessage.success('头像上传成功')
    options.onSuccess()
    
    // 刷新用户信息，确保所有数据最新
    await fetchUserInfo()
  } catch (error) {
    console.error('上传头像失败:', error)
    let errorMessage = '上传头像失败，请稍后重试'
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage = error.response.data.message
    }
    ElMessage.error(errorMessage)
    options.onError(error)
  }
}

// 上传前校验
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像必须是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 修改密码
const handleChangePassword = () => {
  passwordDialogVisible.value = true
}

// 跳转到地址管理页面
const handleGoToAddress = () => {
  router.push('/address')
}

// 提交密码修改
const handlePasswordSubmit = async () => {
  try {
    passwordFormRef.value.validate(async (valid) => {
      if (valid) {
        passwordSubmitting.value = true
        try {
          const response = await userApi.changePassword(passwordForm)
          console.log('修改密码响应:', response)
          
          ElMessage.success('密码修改成功，请重新登录')
          passwordDialogVisible.value = false
          
          // 清空密码表单
          passwordForm.currentPassword = ''
          passwordForm.newPassword = ''
          passwordForm.confirmPassword = ''
          
          // 跳转到登录页
          setTimeout(() => {
            removeToken()
            router.push('/login')
          }, 1500)
        } catch (error) {
          console.error('修改密码失败:', error)
          ElMessage.error('修改密码失败，请稍后重试')
        } finally {
          passwordSubmitting.value = false
        }
      }
    })
  } catch (error) {
    console.error('提交密码修改失败:', error)
    ElMessage.error('修改密码失败，请稍后重试')
    passwordSubmitting.value = false
  }
}

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.profile-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-content {
  padding-top: 20px;
}

.avatar-section {
  text-align: center;
  margin-bottom: 30px;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  cursor: pointer;
}

.avatar-hint {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

.profile-form {
  margin-bottom: 30px;
}

.profile-detail-section {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.profile-detail-section h3 {
  margin-bottom: 20px;
  color: #303133;
}

.form-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}

.account-security {
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.account-security h3 {
  margin-bottom: 15px;
  color: #303133;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
}
</style>